// router.js (更新后的路由)
import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { markRouteVerified, isRouteVerified } from '@/utils/navigation';

const routes = [
  {
    path: '/',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue'),
    props: (route) => ({ inviterId: route.query.inviterId }), // 接收邀请人ID参数
  },
  {
    path: '/register',
    name: 'Register',
    redirect: to => {
      // 保留原始查询参数（特别是inviterId）并重定向到首页
      return { path: '/', query: to.query };
    }
  },
  {
    path: '/set-password',
    name: 'SetPassword',
    component: () => import('@/views/auth/SetPassword.vue'),
  },
  {
    path: '/main',
    name: 'Main',
    component: () => import('@/views/Main.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: 'screening',
        name: 'Screening',
        component: () => import('@/views/Screening.vue'),
        meta: { showAd: true, requiresAuth: true },
      },
      {
        path: 'export',
        name: 'Export',
        component: () => import('@/views/Export.vue'),
        meta: { requiresAuth: true },
      },
      {
        path: 'quota',
        name: 'Quota',
        component: () => import('@/views/Quota.vue'),
        meta: { requiresAuth: true },
      },
      {
        path: 'recharge',
        name: 'Recharge',
        component: () => import('@/views/Recharge.vue'),
        meta: { requiresAuth: true },
      },
      {
        path: 'support',
        name: 'Support',
        component: () => import('@/views/Support.vue'),
        meta: { requiresAuth: true },
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 预设主页和筛查页面为已验证状态，确保首次访问时不会重定向
markRouteVerified('/main');
markRouteVerified('/main/screening');

router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  
  // 检查认证状态（同时检查token和isAuthenticated，确保登录后立即生效）
  const isAuth = userStore.isAuthenticated || !!userStore.token || !!localStorage.getItem('token');
  
  console.log('路由守卫检查:', {
    to: to.path,
    from: from.path,
    requiresAuth: to.meta.requiresAuth,
    isAuthenticated: userStore.isAuthenticated,
    hasToken: !!userStore.token,
    hasLocalStorageToken: !!localStorage.getItem('token'),
    isAuth: isAuth
  });
  
  if (to.meta.requiresAuth && !isAuth) {
    console.log('❌ 未认证，跳转到登录页');
    next('/'); // 未认证跳转到首页
    return; // 立即返回，避免继续执行
  }
  
  // 已认证或不需要认证
  if (to.path === '/' && isAuth) {
    console.log('✅ 已登录用户访问登录页，重定向到主页');
    next('/main/screening');
    return;
  }
  
  {
    // 如果路由需要认证，检查该路由是否已经验证过权限
    if (to.meta.requiresAuth) {
      // 检查该路径是否已经验证过权限
      if (isRouteVerified(to.path)) {
        // 如果已验证，直接通过
        next();
      } else {
        // 如果没验证过，标记为已验证并放行
        markRouteVerified(to.path);
        
        // 仅在从登录页面跳转时重置广告弹窗状态
        if (from.name === 'Login' && to.meta.showAd) {
          console.log('Navigating from Login, resetting adPopupMinimized');
          localStorage.setItem('adPopupMinimized', 'false'); // 重置为最大化
        }
        
        next();
      }
    } else {
      next();
    }
  }
});

export default router;